//package com.mall.thirdPart.controller;
//
//import com.aliyun.sts20150401.models.AssumeRoleResponse;
//import com.aliyun.sts20150401.models.AssumeRoleResponseBody;
//import com.aliyun.tea.TeaException;
//import com.aliyun.oss.common.utils.BinaryUtil;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.mall.common.utils.R;
//import com.mall.thirdPart.utils.DateUtils;
//import org.apache.commons.codec.binary.Base64;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.http.ResponseEntity;
//import org.springframework.stereotype.Controller;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import javax.annotation.PostConstruct;
//import javax.crypto.Mac;
//import javax.crypto.spec.SecretKeySpec;
//import java.time.*;
//import java.util.*;
//
//@RestController
//@RequestMapping("oss")
//public class WebController {
//    private static final Logger logger = LoggerFactory.getLogger(WebController.class);
//
//    @Value("${spring.cloud.alicloud.access-key}")
//    private String accessKeyId;
//
//    @Value("${spring.cloud.alicloud.secret-key}")
//    private String accessKeySecret;
//
//    @Value("${spring.cloud.alicloud.acm.ram-role-name}")
//    private String stsRoleArn;
//
//    @Value("${spring.cloud.alicloud.oss.bucket}")
//    private String bucket;
//
//    @Value("${spring.cloud.alicloud.oss.endpoint}")
//    private String endpoint;
//
//    @Value("${spring.cloud.alicloud.oss.region}")
//    private String region;
//
//    // 设置上传回调URL（即回调服务器地址），必须为公网地址。用于处理应用服务器与OSS之间的通信，OSS会在文件上传完成后，把文件上传信息通过此回调URL发送给应用服务器。
//    private String host ;
//
//    // 使用 @PostConstruct 在依赖注入后初始化
//    @PostConstruct
//    public void initHost() {
//        if (bucket != null && endpoint != null) {
//            this.host = "https://" + bucket + "." + endpoint;
//            logger.info("Host initialized: {}", host);
//        } else {
//            logger.error("Failed to initialize host: bucket = {}, endpoint = {}", bucket, endpoint);
//            throw new IllegalStateException("Bucket or endpoint is null");
//        }
//    }
//
//
//    // 限定上传到OSS的文件前缀。
//    private String upload_dir = DateUtils.formatDate(LocalDate.now(), "yyyy-MM-dd") + "-";
//
//    // 指定过期时间，单位为秒。
//    private Long expire_time = 3600L;
//
//    /**
//     * 通过指定有效的时长（秒）生成过期时间。
//     *
//     * @param seconds 有效时长（秒）。
//     * @return ISO8601 时间字符串，如："2014-12-01T12:00:00.000Z"。
//     */
//    public static String generateExpiration(long seconds) {
//        // 获取当前时间戳（以秒为单位）
//        long now = Instant.now().getEpochSecond();
//        // 计算过期时间的时间戳
//        long expirationTime = now + seconds;
//        // 将时间戳转换为Instant对象，并格式化为ISO8601格式
//        Instant instant = Instant.ofEpochSecond(expirationTime);
//        // 定义时区为UTC
//        ZoneId zone = ZoneOffset.UTC;
//        // 将 Instant 转换为 ZonedDateTime
//        ZonedDateTime zonedDateTime = instant.atZone(zone);
//        return DateUtils.formatDateTime(zonedDateTime, "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
//    }
//
//    // 初始化STS Client
//    public static com.aliyun.sts20150401.Client createStsClient(String accessKeyId, String accessKeySecret) throws Exception {
//        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
//                .setAccessKeyId(accessKeyId)
//                .setAccessKeySecret(accessKeySecret);
//        // Endpoint 请参考 https://api.aliyun.com/product/Sts
//        config.endpoint = "sts.cn-hangzhou.aliyuncs.com";
//        return new com.aliyun.sts20150401.Client(config);
//    }
//
//    /**
//     * 获取STS临时凭证
//     *
//     * @return AssumeRoleResponseBodyCredentials 对象
//     */
//    public AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials getCredential() throws Exception {
//        com.aliyun.sts20150401.Client client = WebController.createStsClient(accessKeyId, accessKeySecret);
//        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
//                .setRoleArn(stsRoleArn)
//                .setRoleSessionName("yourRoleSessionName");// 自定义会话名称
//        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
//        try {
//            AssumeRoleResponse response = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
//            return response.body.credentials;
//        } catch (TeaException error) {
//            logger.error("Failed to get STS credentials: {}", error.getMessage(), error);
//            throw new RuntimeException("Failed to get STS credentials: " + error.getMessage(), error);
//        } catch (Exception _error) {
//            logger.error("Failed to get STS credentials: {}", _error.getMessage(), _error);
//            throw new RuntimeException("Failed to get STS credentials: " + _error.getMessage(), _error);
//        }
//    }
//
//    @GetMapping("/policy")
//    public R getPostSignatureForOssUpload() throws Exception {
//        AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials sts_data = getCredential();
//        String date = DateUtils.formatDate(LocalDate.now(), "yyyyMMdd");
//        String x_oss_date = DateUtils.formatDateTime(ZonedDateTime.now().withZoneSameInstant(ZoneOffset.UTC), "yyyyMMdd'T'HHmmss'Z'");
//
//        Map<String, Object> policy = generatePolicy(sts_data, date, x_oss_date);
//        ObjectMapper mapper = new ObjectMapper();
//        String jsonPolicy = mapper.writeValueAsString(policy);
//
//        String stringToSign = new String(Base64.encodeBase64(jsonPolicy.getBytes()));
//        String signature = calculateSignature(sts_data, stringToSign, date);
//
//        Map<String, String> response = new HashMap<>();
//        response.put("accessKeyId", accessKeyId);
//        response.put("accessKeySecret", accessKeySecret);
//        response.put("bucket", bucket);
//        response.put("version", "OSS4-HMAC-SHA256");
//        response.put("policy", stringToSign);
//        response.put("x_oss_credential", sts_data.accessKeyId + "/" + date + "/" + region + "/oss/aliyun_v4_request");
//        response.put("x_oss_date", x_oss_date);
//        response.put("signature", signature);
//        response.put("security_token", sts_data.securityToken);
//        response.put("dir", upload_dir);
//        response.put("host", host);
//
//        return R.ok().put("data",response);
//    }
//
//    private Map<String, Object> generatePolicy(AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials sts_data, String date, String x_oss_date) {
//        String accesskeyid = sts_data.accessKeyId;
//        String securitytoken = sts_data.securityToken;
//
//        String x_oss_credential = accesskeyid + "/" + date + "/" + region + "/oss/aliyun_v4_request";
//
//        ObjectMapper mapper = new ObjectMapper();
//
//        Map<String, Object> policy = new HashMap<>();
//        policy.put("expiration", generateExpiration(expire_time));
//
//        List<Object> conditions = new ArrayList<>();
//
//        Map<String, String> bucketCondition = new HashMap<>();
//        bucketCondition.put("bucket", bucket);
//        conditions.add(bucketCondition);
//
//        Map<String, String> securityTokenCondition = new HashMap<>();
//        securityTokenCondition.put("x-oss-security-token", securitytoken);
//        conditions.add(securityTokenCondition);
//
//        Map<String, String> signatureVersionCondition = new HashMap<>();
//        signatureVersionCondition.put("x-oss-signature-version", "OSS4-HMAC-SHA256");
//        conditions.add(signatureVersionCondition);
//
//        Map<String, String> credentialCondition = new HashMap<>();
//        credentialCondition.put("x-oss-credential", x_oss_credential);
//        conditions.add(credentialCondition);
//
//        Map<String, String> dateCondition = new HashMap<>();
//        dateCondition.put("x-oss-date", x_oss_date);
//        conditions.add(dateCondition);
//
//        conditions.add(Arrays.asList("content-length-range", 1, 10240000));
//        conditions.add(Arrays.asList("eq", "$success_action_status", "200"));
//        conditions.add(Arrays.asList("starts-with", "$key", upload_dir));
//
//        policy.put("conditions", conditions);
//
//        return policy;
//    }
//
//    private String calculateSignature(AssumeRoleResponseBody.AssumeRoleResponseBodyCredentials sts_data, String stringToSign, String date) {
//        String accesskeysecret = sts_data.accessKeySecret;
//
//        byte[] dateKey = hmacsha256(("aliyun_v4" + accesskeysecret).getBytes(), date);
//        byte[] dateRegionKey = hmacsha256(dateKey, region);
//        byte[] dateRegionServiceKey = hmacsha256(dateRegionKey, "oss");
//        byte[] signingKey = hmacsha256(dateRegionServiceKey, "aliyun_v4_request");
//
//        byte[] result = hmacsha256(signingKey, stringToSign);
//        return BinaryUtil.toHex(result);
//    }
//
//    public static byte[] hmacsha256(byte[] key, String data) {
//        try {
//            // 初始化HMAC密钥规格，指定算法为HMAC-SHA256并使用提供的密钥。
//            SecretKeySpec secretKeySpec = new SecretKeySpec(key, "HmacSHA256");
//
//            // 获取Mac实例，并通过getInstance方法指定使用HMAC-SHA256算法。
//            Mac mac = Mac.getInstance("HmacSHA256");
//            // 使用密钥初始化Mac对象。
//            mac.init(secretKeySpec);
//
//            // 执行HMAC计算，通过doFinal方法接收需要计算的数据并返回计算结果的数组。
//            byte[] hmacBytes = mac.doFinal(data.getBytes());
//
//            return hmacBytes;
//        } catch (Exception e) {
//            throw new RuntimeException("Failed to calculate HMAC-SHA256", e);
//        }
//    }
//}
//
